<?php


namespace UeFiles;


class Door extends Cg
{
    /**
     * @param $res
     * @return \think\response\Json
     */
    public function index($res)
    {
        $result = null;
        $cg = self::$ary; //获取配置信息
        switch ($res->get('action')) {
            case "config": //默认配置
                $result = $cg;
                break;
            case "uploadimage": //上传图片
            case "uploadfile": //上传文件
                $result = $this->UpFiles($res);
                break;
            case "listimage": //在线图片
            case "listfile": //在线文件
                $result = $this->listObj($res);
                break;
            case 'catchimage': //在线抓取
                $result = $this->crawler($res);
                break;
            default:
                $result = array('state' => '请求地址出错');
                break;
        }
        return json($result);
    }


    /**
     * @param $res
     * @return array
     */
    private function UpFiles($res)
    {
        /* 上传配置 */
        $base64 = "upload";
        $fieldName = "";
        $config = array();
        switch (htmlspecialchars($res->get('action'))) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => self::$ary['imagePathFormat'],
                    "maxSize" => self::$ary['imageMaxSize'],
                    "allowFiles" => self::$ary['imageAllowFiles']
                );
                $fieldName = self::$ary['imageFieldName'];
                break;
            case 'uploadfile':
                $config = array(
                    "pathFormat" => self::$ary['filePathFormat'],
                    "maxSize" => self::$ary['fileMaxSize'],
                    "allowFiles" => self::$ary['fileAllowFiles']
                );
                $fieldName = self::$ary['fileFieldName'];
                break;
        }
        /* 生成上传实例对象并完成上传 */
        $UpFileClass = new Uploader($fieldName, $config, $base64);
        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array("state" => "","url" => "","title" => "","original" => "","type" => "","size" => "")
         * 上传状态，上传成功时必须返回"SUCCESS",返回的地址,新文件名,原始文件名,文件类型,文件大小
         */
        return $UpFileClass->getFileInfo();
    }

    /**
     * @param $res
     * @return array
     */
    private function listObj($res)
    {
        switch ($res->get('action')) {
            case 'listfile': /* 列出文件 */
                $allowFiles = self::$ary['fileManagerAllowFiles'];
                $listSize = self::$ary['fileManagerListSize'];
                $path = self::$ary['fileManagerListPath'];
                break;
            case 'listimage': /* 列出图片 */
            default:
                $allowFiles = self::$ary['imageManagerAllowFiles'];
                $listSize = self::$ary['imageManagerListSize'];
                $path = self::$ary['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
        /* 获取参数 */
        $size = $res->get('size') ? htmlspecialchars($res->get('size')) : $listSize;
        $start = $res->get('start') ? htmlspecialchars($res->get('start')) : 0;
        $end = $start + $size;
        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return array("state" => "no match file", "list" => array(), "start" => $start, "total" => count($files));
        }
        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }
        /* 返回数据 */
        return array("state" => "SUCCESS", "list" => $list, "start" => $start, "total" => count($files));
    }

    private function crawler($res)
    {
        /* 上传配置 */
        $config = array(
            "pathFormat" => self::$ary['catcherPathFormat'],
            "maxSize" => self::$ary['catcherMaxSize'],
            "allowFiles" => self::$ary['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = self::$ary['catcherFieldName'];

        /* 抓取远程图片 */
        $list = array();
        if ($res->post($fieldName)) {
            $source = $res->post[$fieldName];
        } else {
            $source = $res->get[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new Uploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }
        /* 返回抓取数据 */
        return array('state' => count($list) ? 'SUCCESS' : 'ERROR', 'list' => $list);
    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = array(
                            'url' => substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime' => filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }
}